package com.xmy.aboutThread;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

// 管道通信 pipe
public class Demo6 {

    static class RThread implements Runnable {

        private PipedReader reader;

        public RThread(PipedReader reader) {
            this.reader = reader;
        }

        @Override
        public void run() {
            System.out.println("i am reader");

            int receive;

            try {
                while ((receive = reader.read()) != -1) {
                    System.out.print((char)receive);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class WThread implements Runnable {

        PipedWriter writer;

        public WThread(PipedWriter writer) {
            this.writer = writer;
        }

        @Override
        public void run() {
            System.out.println("i am writer");

            try {
                writer.write("test");
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) throws IOException, InterruptedException {

        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader();

        writer.connect(reader);

        new Thread(new WThread(writer)).start();
        Thread.sleep(1000);

        new Thread(new RThread(reader)).start();

    }
}
